<template>
  <div v-if="loaded">
    <div class="top-model">
      <header-bar :addTab="clickNav" :menuId="menuId"></header-bar>
      <!-- <header-nav :addTab="clickNav" :reload="reloadTabContent"></header-nav> -->
    </div>
    <div class="main-model">
      <p class="refresh-icon">
        <i class="iconfont icon-refresh" @click="reloadTabContent" style="margin-right:10px;"></i>
        <i class="iconfont icon-close" @click="closeAllTabContent"></i>
      </p>
      <p class="time">
        <span class="iconfont icon-time"></span>
        {{nowTime}}
      </p>
      <el-tabs
        class="header-menu-tabs"
        v-model="editableTabsValue"
        type="card"
        :closable="editableTabs.length>1"
        @tab-remove="removeTab"
        @tab-click="clickTab"
      >
        <el-tab-pane v-for="item in editableTabs" :key="item.name" :name="item.name">
          <span slot="label">
            <i class="iconfont icon-dot"></i>
            {{item.title}}
          </span>
          <!-- 面包屑 -->
          <!-- <el-breadcrumb v-if="item.breadcrumbArr" separator-class="el-icon-arrow-right">
            <el-breadcrumb-item v-for="(obj, i) in item.breadcrumbArr" :key="i">{{obj}}</el-breadcrumb-item>
          </el-breadcrumb>-->
          <template v-if="item.isIframe">
            <iframe :name="item.name" :src="item.content" width="100%" height="100%"></iframe>
          </template>
          <div v-else-if="!reload[item.name]" class="router-view">
            <keep-alive>
              <router-view v-if="item.name === menuId" />
            </keep-alive>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import HeaderBar from '@/components/HeaderBar/Main'
import HeaderNav from '@/components/Nav/Main'
import { getOrgList } from '@/api/org'
import { mapMutations } from 'vuex'

var headertime = null
export default {
  name: 'MainContent',
  data() {
    return {
      nowTime: '',
      loaded: true,
      editableTabsValue: '',
      menuId: 'home',
      editableTabs: [],
      reload: {},
    }
  },
  components: {
    HeaderBar,
    HeaderNav,
  },
  created() {
    let that = this
    // 大屏跳转pc端 ----》按esc关闭
    let isClient = localStorage.getItem('isClient')
    document.onkeydown = function (e) {
      if (e && e.keyCode == 27 && isClient) {
        // 按 Esc
        window.ws ? window.ws.close() : ''
        that.closeResetAlarm()
        window.external.closeDetailsPage(10111)
      }
    }

    that.time()

    // that.$store.dispatch("setUserInfo", function () {
    //   // 为获取到用户信息，跳转登录
    //   if (!that.$store.state.userinfo) {
    //     let userinfo =
    //       (localStorage.getItem("userInfo")
    //         ? JSON.parse(localStorage.getItem("userInfo"))
    //         : "") || this.$store.state.userinfo;
    //     localStorage.removeItem("userInfo");
    //     // 断开webscoket
    //     window.ws ? window.ws.close() : "";
    //     that.$router.push({
    //       path: "/login",
    //       query: userinfo
    //         ? userinfo.loginId
    //           ? { loginId: userinfo.loginId }
    //           : {}
    //         : {},
    //     });
    //   }
    //   that.loaded = true;
    // });

    // 缓存单位列表
    getOrgList({ queryType: 0 }).then((data) => {
      this.setOrgOptions(data.data)
    })
  },
  mounted() {
    this.menuId = this.$route.name
    this.addTab(this.$route.name, this.$route.meta.title)
  },
  activated() {
    this.menuId = this.$route.name
  },
  methods: {
    ...mapMutations(['setOrgOptions']),
    // 点击菜单
    clickNav(key, keyPath) {
      let targetName = key
      let newTabName = targetName
      let dom = event.currentTarget
      let title = dom.textContent
      let link = dom.getAttribute('data-link')
      let isIframe = link && link.indexOf('/') > -1 ? true : false // 判断key是页面地址还是模块名称
      if (this.menuId === newTabName) return
      this.$router.push({ name: newTabName })
      this.addTab(newTabName, title, false, isIframe, link)
    },
    /*
     * 【参数说明】：
     *    tabName    内容的模块名称
     *    title      展示的tab标签文本
     *    parames    模块/页面附带的参数
     *    isIframe   是否为iframe嵌入
     *    link       嵌入iframe的地址
     */
    addTab(tabName, title, parames, isIframe, link) {
      let newTabName = tabName
      // 如果标签页未打开过
      if (
        !this.editableTabs.filter((n) => {
          return n.name == newTabName
        }).length
      ) {
        let obj = {
          title: title,
          name: newTabName,
          content: isIframe ? './rdsp/' + link : newTabName,
          fatherType: 1,
          isIframe: isIframe,
          parames: parames || false,
          breadcrumbArr: [],
        }
        obj[newTabName + 'Show'] = true
        this.editableTabs.push(obj)
        this.editableTabsValue = newTabName
        // this.getBreadCrumbsText(link || newTabName, this.editaTabIndex);
      }
    },
    removeTab(name) {
      const tabs = this.editableTabs
      let activeName = ''
      // 关闭的是当前选中的tab
      if (this.editableTabsValue === name) {
        tabs.forEach((tab, index) => {
          if (tab.name === this.editableTabsValue) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
            }
          }
        })
        this.clickTab({ name: activeName })
      }
      this.editableTabs = tabs.filter((tab) => tab.name !== name)
    },
    clickTab(obj, event) {
      if (this.menuId === obj.name) {
        return
      } else {
        this.menuId = obj.name
        this.$router.push({ name: obj.name })
      }
    },
    // 计算面包屑
    getBreadCrumbsText(link, index) {
      let menuList = this.$store.state.userinfo.resources
      let arr = []
      let selectId = ''
      var matchName = (id) => {
        for (var i = 0, len = menuList.length; i < len; i++) {
          if (menuList[i].resourceId == id) {
            if (menuList[i].parentId) {
              arr.unshift(menuList[i].resourceName)
              // 继续向上查找
              matchName(menuList[i].parentId)
            } else {
              arr.unshift(menuList[i].resourceName)
              return false
            }
          }
        }
      }
      for (var i = 0, len = menuList.length; i < len; i++) {
        if (menuList[i].link == link.trim()) {
          if (menuList[i].parentId) {
            arr.unshift(menuList[i].resourceName)
            // 继续向上查找
            matchName(menuList[i].parentId)
          } else {
            arr.unshift(menuList[i].resourceName)
          }
        }
      }
    },
    // 刷新tab页内容
    reloadTabContent() {
      // 当前操作的tab name
      let currentTabName = this.editableTabsValue
      var tabItem = this.editableTabs.filter((n) => {
        return n.name == currentTabName
      })[0]
      if (tabItem.isIframe) {
        $('iframe[name=' + currentTabName + ']')[0].src = tabItem.content
      } else {
        this.$set(this.reload, currentTabName, true)
        this.$nextTick(() => {
          this.$set(this.reload, currentTabName, false)
        })
      }
    },
    // 关闭所有tab页签
    closeAllTabContent() {
      if (this.editableTabsValue !== 'home') {
        this.$router.push({
          name: 'home',
        })
      }
      this.editableTabs = [
        {
          title: '看板',
          name: 'home',
          content: 'home',
          fatherType: 1,
          homeShow: true,
        },
      ]
    },
    // 已复位警情
    closeResetAlarm() {
      if (this.editableTabsValue !== 'resetAlarm') {
        this.$router.push({
          name: 'resetAlarm',
        })
      }
      this.editableTabs = [
        {
          title: '已复位警情',
          name: 'resetAlarm',
          content: 'resetAlarm',
          fatherType: 1,
          homeShow: true,
        },
      ]
    },
    fatherMethod(type, param) {
      if (type == 1) {
        //图片预览
      }
    },
    time() {
      clearTimeout(headertime) // 清除定时器
      var dt = new Date()
      var year = dt.getFullYear()
      var month = dt.getMonth() + 1 // (0-11,0代表1月)
      var date = dt.getDate() // 获取天
      var num = dt.getDay() // 获取星期
      var weekday = [
        '星期日',
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六',
      ]
      var hour = dt.getHours() // 获取时
      var minute = dt.getMinutes() // 获取分
      var second = dt.getSeconds() // 获取秒
      // 分秒时间是一位数字，在数字前补0。
      date = this.extra(date)
      month = this.extra(month)
      minute = this.extra(minute)
      second = this.extra(second)
      this.nowTime =
        year +
        ' 年 ' +
        month +
        ' 月 ' +
        date +
        ' 日 ' +
        weekday[num] +
        ' ' +
        hour +
        ':' +
        minute +
        ':' +
        second
      headertime = setTimeout(this.time, 1000) //设定定时器，循环运行
    },
    extra(x) {
      //如果传入数字小于10，数字前补一位0。
      if (x < 10) {
        return '0' + x
      } else {
        return x
      }
    },
  },
  watch: {
    editableTabsValue(val, oldVal) {
      this.$store.state.currentTabName = val
    },
    $route(to, from) {
      if (
        this.editableTabs.filter((n) => {
          return n.name === to.name
        }).length === 0
      ) {
        this.editableTabs = this.editableTabs.concat([
          {
            name: to.name,
            content: to.name,
            title: to.meta.title,
          },
        ])
      }
      this.editableTabsValue = to.name
      this.menuId = to.name
    },
  },
}
</script>

<style lang="scss">
iframe {
  position: absolute;
  top: 0;
  left: 0;
  border: none;
}
.main-model {
  position: relative;
  .refresh-icon,
  .time {
    position: absolute;
    top: 0;
    height: 48px;
    line-height: 48px;
    color: #446bde;
    background-color: #f6f8fc;
  }
  .refresh-icon {
    padding-right: 15px;
    width: 80px;
    text-align: right;
    font-size: 22px;
    i {
      height: 100%;
      font-size: 20px;
      cursor: pointer;
    }
  }
  .time {
    display: flex;
    align-items: center;
    width: 295px;
    right: 0;
    font-size: 14px;
    .iconfont {
      border-left: 1px solid #ddd;
      height: 28px;
      line-height: 28px;
      padding-left: 12px;
      margin-right: 5px;
      font-size: 14px;
    }
  }
  .header-menu-tabs {
    & > .el-tabs__header {
      &:first-child {
        width: calc(100% - 80px - 295px);
        height: 48px;
        margin-left: 80px;
        background-color: #f6f8fc;
        border: none;
        margin-bottom: 0;
        .el-tabs__nav-wrap {
          height: 48px;
          .el-tabs__nav-scroll {
            height: 48px;
            display: flex;
            align-items: center;
            .el-tabs__nav {
              height: 36px;
              line-height: 34px;
              border: none;
              .el-tabs__item {
                margin: 0 5px;
                padding: 0 10px;
                height: 36px;
                line-height: 32px;
                border: 1px solid #dcdfe6;
                border-radius: 5px;
                color: #606266;
                background-color: #fff;
                .iconfont {
                  margin-right: 6px;
                  color: #d5d8de;
                }
                .el-icon-close {
                  font-size: 16px;
                }
              }
              .el-tabs__item.is-active {
                color: #446bde;
                border-color: #446bde;
                span {
                  color: #446bde;
                  .iconfont {
                    color: #446bde;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
.el-breadcrumb {
  padding-bottom: 10px;
}
.router-view {
  overflow-y: auto;
  height: calc(100vh - 96px);
  & > div {
    padding: 20px;
  }
}
</style>
